package edu.zjut.sjq.service;

import edu.zjut.sjq.bean.Like;
import edu.zjut.sjq.bean.User;
import edu.zjut.sjq.mapper.LikeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * Created by sue on 2017/3/18.
 */
@Service
public class LikeService {
    @Autowired
    private LikeMapper likeMapper;
    @Autowired
    private HttpSession session;

    // 点赞或者取消赞
    public Integer addOrRemove( Integer articleId){
        User user = (User) session.getAttribute("user");
        if (user==null)
            return 2;
        Like record = likeMapper.selectByArticleIdAndUserId(articleId, user.getId());

        if (record==null){
            // 点赞
            Like like=new Like();
            like.setArticleId(articleId);
            like.setUserId(user.getId());
            like.setCreateTime(new Date());
            return likeMapper.insert(like);
        }else {
            // 取消赞
            return likeMapper.deleteByPrimaryKey(record.getId());
        }

    }

    // 获取赞的数量
    public Integer getTotalLikeNum(Integer articleId){
        return likeMapper.selectTotalLikeNum(articleId);
    }


}
